/*******************************************************************************
 * Copyright (c) 2010 liw.
 * All rights reserved. 
 * 
 * This file is part of VanBus.
 * 
 *     VanBus is free software: you can redistribute it and/or modify
 *     it under the terms of the GNU General Public License as published by
 *     the Free Software Foundation, either version 3 of the License, or
 *     (at your option) any later version.
 * 
 *     VanBus is distributed in the hope that it will be useful,
 *     but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
 * 
 *     You should have received a copy of the GNU General Public License
 *     along with VanBus.  If not, see <http://www.gnu.org/licenses/>.
 * Contributors:
 *     liw - initial API and implementation
 ******************************************************************************/
package org.niclab.vanbus.query.ws;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.JsonToken;
import org.codehaus.jackson.map.ObjectMapper;
import org.niclab.vanbus.R;
import org.niclab.vanbus.activity.controller.BusStopController;
import org.niclab.vanbus.application.VanBusApplication;
import org.niclab.vanbus.model.BusRoute;
import org.niclab.vanbus.model.BusStop;
import org.niclab.vanbus.model.viewadpater.BusStopArrayAdapter;
import org.niclab.vanbus.model.viewadpater.CommonListAdapter;
import org.niclab.vanbus.query.AsyncQueryTask;
import org.niclab.vanbus.query.handler.IProgressAware;

import android.content.Context;
import android.util.Log;

public class RouteStopsWithTimesWSQueryResResolver extends BaseResponseResolver<RouteStopsWithTimesWSQueryResResolver.QueryResult> implements IProgressAware{

	public static class QueryResult{
		List<BusStop> stops = new ArrayList<BusStop>();
		Map<String, List<String>> times= new HashMap<String,List<String>>();
		
		/**
		 * @param stop stop to add
		 * 
		 */
		public void addStop(BusStop stop){
			stops.add(stop);
		}
		
		
		/**
		 * @return a list of stops
		 */
		public List<BusStop> getStops(){
			return stops;
		}
		
		/**
		 * @param stopId the stopId
		 * @param time a list of times for stopId
		 */
		public void putTimes(String stopId,List<String> time){
			times.put(stopId,time);
		}
		
		/**
		 * 
		 * @param stopId
		 * @return times for stop with stopId
		 */
		public List<String> getTimes(String stopId){
			return times.get(stopId);
		}
	}
	
	private static final String LOG_TAG="RouteStopsWithTimesWSQueryResHandler";
	private AsyncQueryTask task;

	
	@Override
	protected QueryResult interpret(HttpEntity entity) {

		JsonFactory jsonFactory = VanBusApplication.getInstance().getJsonFactory();
		InputStream inputStream = null;
		//BusStopController stopCtr = new BusStopController(context);
		try {
			inputStream = entity.getContent();
		} catch (IllegalStateException e) {
			Log.d("LOG_TAG", "HttpEntity exception");
			e.printStackTrace();
		} catch (IOException e) {
			Log.d("LOG_TAG","HttpEntity IOException");
			e.printStackTrace();
		}
		
		if(inputStream ==null)
			return null;
		
		
		try {
			JsonParser parser = jsonFactory.createJsonParser(inputStream);
			parser.setCodec(new ObjectMapper(jsonFactory));
			
			if(parser.nextToken()!=JsonToken.START_ARRAY)
				return null;
			

			QueryResult result = new QueryResult();
			JsonToken token=null;
			HashSet<String> ignoredFields = new HashSet<String>();
			ignoredFields.add("direction");
			ignoredFields.add("favourite");
			ignoredFields.add("routeID");
			ignoredFields.add("routeName");
			
			int stopCount=0;
			while((token = parser.nextToken()) !=JsonToken.END_ARRAY){
				
				if(token.asString().equals(","))
					token=parser.nextToken();
				
				
				if(token!=JsonToken.START_OBJECT)
					//return stopList;
					return result;
				
				BusStop stop = new BusStop();
				
				
				while(parser.nextToken()!= JsonToken.END_OBJECT){
					String propertyName = parser.getCurrentName();
					parser.nextToken();
					
					if(propertyName == "stopName"){
						stop.setStopName(parser.getText());
					}else if(propertyName == "stopID"){
						stop.setStopId(parser.getText());
					}else if(propertyName == "times"){
						List<String> times = (List<String>)parser.readValueAs(Object.class);
						result.putTimes(stop.getStopId(), times);

						
					}else if(ignoredFields.contains(propertyName)){
						parser.getText();
					}
				}
				stopCount++;
				result.addStop(stop);
				
				if(stopCount%3 ==0 && task!=null)
					task.postProgress("continue");
					
					
					
				
				
			}

			Log.d(LOG_TAG,"stopList size:"+ result.getStops().size());
			return result;
			
		} catch (JsonParseException e) {
			Log.d("LOG_TAG", "JsonParseException");
			e.printStackTrace();
		} catch (IOException e) {
			Log.d("LOG_TAG","JSONParser IOException");
			e.printStackTrace();
		}
		
		return null;
	}



	@Override
	public void setAsyncQueryTask(AsyncQueryTask task) {
		this.task = task;
		
	}
	
	

}
